//
//  SecondViewController.m
//  shouji138
//
//  Created by administrator on 8/27/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SecondViewController.h"
#import "SrnTeacherAppDelegate.h"
#import "SwitchViewController.h"
#import "user.h"

#define ROW_HEIGHT 60

@implementation SecondViewController

@synthesize myscrollView,dateFormatter;
#pragma mark Table View Controller Methods;


-(IBAction)clearButtonClick:(id)sender{
	[[SrnTeacherAppDelegate App].listOfItems removeAllObjects];
	[myscrollView reloadData];
	[udb deleteOneQuestion:currSid];
}

-(IBAction)reportButtonClick:(id)sender{
	
	//User *user = [User alloc];
	//user.uid = 111;
	//user.username = @"zx";
	//user.choice = @"B";
	//user.num = 222;
	
	//udb =[db alloc];
	//BOOL re = [udb open];
	//BOOL re1 = [udb insertOneChoice:user];
	//[udb close];
	
	
	//[udb delete];
	//[udb getResults:users];
}

-(IBAction)newClick:(id)sender{
	[SrnTeacherAppDelegate App].currid++; 
	currSid = [SrnTeacherAppDelegate App].currid;
	[SrnTeacherAppDelegate App].isNew = YES;
	sessionState.text = @"New";
	NSLog(@"new clicked!");
}

-(IBAction)saveClick:(id)sender{
	//[udb updateFlag:currSid];
	
	NSLog(@"save clicked!");
	[refile deleteFile];
	NSMutableArray	 *users;
	users = [[NSMutableArray alloc] init];
	[udb getResults:users];
	[udb delete];
	
	MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
	controller.mailComposeDelegate = self;
	[controller setSubject:@"Mindtally Vote Results"];
	[controller setMessageBody:@"Hi \r\n voting results from mindtally" isHTML:NO];
	
	//attach file to the mail.
	//NSString  *paths = [[NSBundle mainBundle] resourcePath];
	//NSString *path = [paths stringByAppendingString:@"results.csv"];
    NSString *path = [refile getPath];
	NSData *myData = [NSData dataWithContentsOfFile:path];
	[controller addAttachmentData:myData mimeType:@"text/csv" fileName:@"results.csv"];
	
	[self presentModalViewController:controller animated:YES];
	[controller release];
}

-(IBAction)closeClick:(id)sender{
	[SrnTeacherAppDelegate App].isNew = NO;
	[SrnTeacherAppDelegate App].isOpen = NO;
	[SrnTeacherAppDelegate App].isClose = YES;
	[[SrnTeacherAppDelegate App].listOfItems removeAllObjects];
	[myscrollView reloadData];	
	NSLog(@"close clicked!");
	sessionState.text = @"Closed";
}

-(IBAction)showClick:(id)sender{

	[SrnTeacherAppDelegate App].isHide = NO;
	NSLog(@"show clicked!");
	sessionState.text = @"Show";
}

-(IBAction)hideClick:(id)sender{
	[SrnTeacherAppDelegate App].isHide = YES;
	NSLog(@"hide clicked!");
	sessionState.text = @"Hide";
}

-(IBAction)openClick:(id)sender{
	if ([SrnTeacherAppDelegate App].isNew == NO) {
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warnning"
			message:@"You Should Firstly Click New Button!"
			delegate:self
			cancelButtonTitle:nil
		    otherButtonTitles:@"Ok",nil];
		
	[alertView show];
	[alertView release];	
	}
	[SrnTeacherAppDelegate App].isOpen = YES;
	NSLog(@"open clicked!");
	sessionState.text = @"Opened";
}

-(IBAction)sendMailClick:(id)sender{
	
	[refile deleteFile];
	NSMutableArray	 *users;
	users = [[NSMutableArray alloc] init];
	[udb getResults:users];
	[udb delete];
	
	MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
	controller.mailComposeDelegate = self;
	[controller setSubject:@"Mindtally Vote Results"];
	[controller setMessageBody:@"Hi \r\n voting results from mindtally" isHTML:NO];
	
	//attach file to the mail.
	//NSString  *paths = [[NSBundle mainBundle] resourcePath];
	//NSString *path = [paths stringByAppendingString:@"results.csv"];
    NSString *path = [refile getPath];
	NSData *myData = [NSData dataWithContentsOfFile:path];
	[controller addAttachmentData:myData mimeType:@"text/csv" fileName:@"results.csv"];
	
	[self presentModalViewController:controller animated:YES];
	[controller release];
	
	//[myData release];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	[self becomeFirstResponder];
	[self dismissModalViewControllerAnimated:YES];
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 -(void)viewDidLoad {
	 //NSArray *array = [[NSArray alloc] initWithObjects:@"one", @"two",@"three",@"four",
	//				   @"none", @"ntwo",@"nthree",@"nfour",@"nnone", @"nntwo",@"nnthree",@"nnfour"];
	// self.listData = array;
	 [super viewDidLoad];
	 
	 self.view.backgroundColor = [UIColor lightGrayColor];
	 
	 ip.text = [SrnTeacherAppDelegate App].ipaddress;
	 port.text = [NSString stringWithFormat:@"%hu",[SrnTeacherAppDelegate App].port];
	 count.text = @"0";
	 
	 //getTime
	 self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
	 [self.dateFormatter setDateStyle:NSDateFormatterNoStyle];
	 [self.dateFormatter setTimeStyle:NSDateFormatterShortStyle];
	 startedTime.text = [self.dateFormatter stringFromDate:[NSDate date]];
	 
	 if ([MFMailComposeViewController canSendMail])
		 sendMailButton.enabled = YES;	
	 
	 udb =[db alloc];
	 BOOL re = [udb open];
	 currSid = [udb getMaxId] + 1;
	 [SrnTeacherAppDelegate App].udb = udb;
	 [SrnTeacherAppDelegate App].currid =  currSid;
	 refile = [file alloc];
	 sessionState.text = @"Closed";
	 myscrollView.hidden = YES;
}

//-(NSString *)getCurrentTime{
//	NSDateFormatterShortStyle
//}

-(void)updateUser
{
	count.text = [NSString stringWithFormat:@"%hu",[SrnTeacherAppDelegate App].userCount];
}

-(void)updateResult:(User *)user
{	
	[[SrnTeacherAppDelegate App].listOfItems addObject:user];
	int i =0;
	for(; i< [[SrnTeacherAppDelegate App].listOfAllUsers count];i++)
	{
		User *tempUser = [[SrnTeacherAppDelegate App].listOfAllUsers objectAtIndex:i];
		if([tempUser.username localizedCompare:user.username] == 0)
		{
			break;
		}
	}
	
	if(i>= [[SrnTeacherAppDelegate App].listOfAllUsers count]){
		[[SrnTeacherAppDelegate App].listOfAllUsers addObject:user];
	}
	//TODO
	user.uid = 1;
	user.num = currSid;
	BOOL re1 = [udb insertOneChoice:user];
	[myscrollView reloadData];
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[SrnTeacherAppDelegate App].listOfItems count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
		cell = [self tableViewCellWithReuseIdentifier:CellIdentifier];
	}
	
	// configureCell:cell forIndexPath: sets the text and image for the cell -- the method is factored out as it's also called during minuted-based updates.
	[self configureCell:cell forIndexPath:indexPath];
    
    // Set up the cell...
	//User *cellValue = [[shouji138AppDelegate App].listOfItems objectAtIndex:indexPath.row];
	//cell.text = cellValue.username;
	
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark Configuring table view cells

#define NAME_TAG 1
#define TIME_TAG 2
#define IMAGE_TAG 3

#define LEFT_COLUMN_OFFSET 10.0
#define LEFT_COLUMN_WIDTH 160.0

#define MIDDLE_COLUMN_OFFSET 170.0
#define MIDDLE_COLUMN_WIDTH 90.0

#define RIGHT_COLUMN_OFFSET 280.0

#define MAIN_FONT_SIZE 18.0
#define LABEL_HEIGHT 26.0

#define IMAGE_SIDE 30.0

- (UITableViewCell *)tableViewCellWithReuseIdentifier:(NSString *)identifier {
	
	/*
	 Create an instance of UITableViewCell and add tagged subviews for the name, local time, and quarter image of the time zone.
	 */
	
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
	
	/*
	 Create labels for the text fields; set the highlight color so that when the cell is selected it changes appropriately.
	 */
	UILabel *label;
	CGRect rect;
	
	
	// Create a label for the time zone name.
	rect = CGRectMake(LEFT_COLUMN_OFFSET, (ROW_HEIGHT - LABEL_HEIGHT) / 2.0, LEFT_COLUMN_WIDTH, LABEL_HEIGHT);
	label = [[UILabel alloc] initWithFrame:rect];
	label.tag = NAME_TAG;
	label.font = [UIFont boldSystemFontOfSize:MAIN_FONT_SIZE];
	label.adjustsFontSizeToFitWidth = YES;
	[cell.contentView addSubview:label];
	label.highlightedTextColor = [UIColor whiteColor];
	[label release];
	
	// Create a label for the time.
	/*
	rect = CGRectMake(MIDDLE_COLUMN_OFFSET, (ROW_HEIGHT - LABEL_HEIGHT) / 2.0, MIDDLE_COLUMN_WIDTH, LABEL_HEIGHT);
	label = [[UILabel alloc] initWithFrame:rect];
	label.tag = TIME_TAG;
	label.font = [UIFont systemFontOfSize:MAIN_FONT_SIZE];
	label.textAlignment = UITextAlignmentRight;
	[cell.contentView addSubview:label];
	label.highlightedTextColor = [UIColor whiteColor];
	[label release];
	 */
	
	// Create an image view for the quarter image.
	rect = CGRectMake(MIDDLE_COLUMN_OFFSET, (ROW_HEIGHT - IMAGE_SIDE) / 2.0, IMAGE_SIDE, IMAGE_SIDE);
	
	UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
	imageView.tag = IMAGE_TAG;
	[cell.contentView addSubview:imageView];
	[imageView release];	
	
	return cell;
}


- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
    
   
	User *cellValue = [[SrnTeacherAppDelegate App].listOfItems objectAtIndex:indexPath.row];
		
	UILabel *label;
	
	// Set the locale name.
	label = (UILabel *)[cell viewWithTag:NAME_TAG];
	label.text = cellValue.username;
	
	// Set the time.
	/*
	 [dateFormatter setTimeZone:wrapper.timeZone];
	label = (UILabel *)[cell viewWithTag:TIME_TAG];
	label.text = [dateFormatter stringFromDate:[NSDate date]];
	*/
	// Set the image.
	UIImageView *imageView = (UIImageView *)[cell viewWithTag:IMAGE_TAG];
	imageView.image = cellValue.image;
}    



// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	if(udb != nil)
	    [udb close];
}


- (void)dealloc {
    [super dealloc];
}


@end
